public class NthSuperUglyNumber {

    public int nthSuperUglyNumber(int n, int[] primes) {
        int m = primes.length;
        int[] dp = new int[n];
        dp[0] = 1;
        int[] p = new int[m];
        for (int i = 1; i < n; i++) {
            int min = Integer.MAX_VALUE;
            for (int j = 0; j < m; j++) {
                min = Math.min(min, dp[p[j]] * primes[j]);
            }
            dp[i] = min;
            for (int j = 0; j < m; j++) {
                if (dp[p[j]] * primes[j] == dp[i]) p[j]++;
            }
        }
        return dp[n - 1];
    }
}
